package com.xindaoapp.happypet.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.OtherActivity;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Fans;
import com.xindaoapp.happypet.bean.Fans.Fan;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class OhterTab3Fragment extends XDBaseFragment {

    private String uid = "";

    private Context mContext;
    private PullToRefreshListView listView;

    private RelativeLayout noresult;


    private FrameLayout fl;

    public static OhterTab3Fragment Instance(Bundle args) {

        final OhterTab3Fragment f = new OhterTab3Fragment();

        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uid = getArguments() != null ? getArguments().getString("uid") : "";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return mView = inflater.inflate(R.layout.fragment_other_tab3, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    private final int currentpage = 1;

    @Override
    protected void initUi() {
        mContext = getActivity();
        listView = (PullToRefreshListView) findViewById(R.id.listview);
        noresult = (RelativeLayout) findViewById(R.id.noresult);
        fl = (FrameLayout) findViewById(R.id.loading);
        initAttention(page);

        listView.setPullRefreshEnabled(true);
        listView.setScrollLoadEnabled(true);

        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                fans.clear();
                page = 1;
                initAttention(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (total == fans.size()) {
                    onLoad();
                    Toast.makeText(mContext, "没有更多了", Toast.LENGTH_SHORT).show();
                } else {
                    page++;
                    initAttention(page);
                }
            }
        });
        listView.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, OtherActivity.class);
                intent.putExtra("uid", fans.get(position).followuid);
                intent.putExtra("name", fans.get(position).fusername);
                intent.putExtra("face", fans.get(position).userface);
                startActivity(intent);
            }
        });
    }

    private int total;
    private final List<Fan> fans = new ArrayList<Fan>();
    private Adapter adapter;

    private void initAttention(int page2) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page2));
        params.put("uid", uid);
        params.put("pagesize", "15");
        AddClient.get(Address.FANSGUANZHU, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                Fans parse = JSON.parseObject(content, Fans.class);
                if (fl.getVisibility() == View.VISIBLE) {
                    fl.setVisibility(View.GONE);
                }
                if (parse.getResult().equals("0")) {
                    if (Integer.parseInt(parse.getTotal()) == 0) {
                        noresult.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                    } else {
                        List<Fan> array = parse.array;
                        if (array.size() > 0) {
                            fans.addAll(array);
                        }
                        if (adapter == null) {
                            adapter = new Adapter(fans);
                            listView.getRefreshableView().setAdapter(adapter);
                        } else {
                            adapter.notifyDataSetChanged();
                        }
                        if (Integer.parseInt(parse.getTotal()) < 10) {
                            listView.setPullRefreshEnabled(false);
                            listView.setScrollLoadEnabled(false);
                        }
                        total = Integer.parseInt(parse.getTotal());
                    }
                }
                onLoad();
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                onLoad();
                super.onFailure(error, content);
            }
        });
    }

    private void onLoad() {
        listView.onPullDownRefreshComplete();
        listView.onPullUpRefreshComplete();
    }

    private class Adapter extends BaseAdapter {
        private final List<Fan> fan;

        public Adapter(List<Fan> fan) {
            super();
            this.fan = fan;
        }

        @Override
        public int getCount() {
            return fan.size();
        }

        @Override
        public Object getItem(int position) {
            return fan.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(getActivity(), R.layout.fans_list_item1, null);
                holder.face = (CircleImageView) convertView.findViewById(R.id.face);
                holder.iv_guanzhu = (ImageView) convertView.findViewById(R.id.iv_guanzhu);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ImageLoader.getInstance().displayImage(fan.get(position).userface, holder.face);
            holder.name.setText(fan.get(position).fusername);
            return convertView;
        }

    }
    class ViewHolder {
        CircleImageView face;
        ImageView iv_guanzhu;
        TextView name;
    }

    private int page = 1;
}
